// pages/vip/qiniu/qiniu.js
const app = getApp()
const qiniuUploader = require('../../../utils/qiniuUploader.js')
const connector = require('../../../utils/connector.js')
  
var tok;
// var sets;//监听websocket是否连接成功（轮询器）
// 初始化七牛相关参数
function initQiniu(tok, domain) {
  var options = {
   region: 'SCN', // 华南区
    // uptokenURL: 'https://minitest.17jxyx.com/api/v1/token/file/goods',
    uptoken: tok,
    uploadURL: 'https://up-z2.qbox.me/',
    domain: domain,
    shouldUseQiniuFileName: false
  };
  qiniuUploader.init(options);
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bar_Height: wx.getSystemInfoSync().statusBarHeight + 45,
    fileJudge:false,//是否正在上传
    progressNum:0,//上传进度
    fileArr:[],//上传的图片集合
  },
  handleContact(e) {
    console.log(e)
    console.log(e.detail.path)
    console.log(e.detail.query)
  },
  //单图片上传
  chatI: function () {
    var that = this;
    // console.log(connector.connector().filePath)
    let obj={
      
    }
    connector.getFunc(app.conUser + connector.connector().filePath, obj, "post", app.tokens,function(res){
      console.log(res)
      // console.log(res.data[0].upToken)
      //sampleGraph
      chatI(that, res.data[0].upToken, res.data[0].domain,"sampleGraph/");

    },function(res){
      console.log(res)

    })
  },
  chatIs: function () {
    var that = this;
    // console.log(connector.connector().filePath)
    let obj = {

    }
    connector.getFunc(app.conUser + connector.connector().filePath, obj, "post", app.tokens, function (res) {
      // console.log(res.data[0].upToken)
      chatI(that, res.data[0].upToken, res.data[0].domain, "head/");

    }, function (res) {
      console.log(res)

    })
  },
  delFile(e){
    let that = this;
    let fileArr = that.data.fileArr
    let key = e.currentTarget.dataset.key //65e
    console.log(e.currentTarget.dataset.key)
    // let fileArrInd;
    for (let i = 0; i < fileArr.length;i++){
      if (key == fileArr[i].key){
        fileArr.splice(i, 1)
      }
    }
    that.setData({
      fileArr: fileArr
    })
    // if (key)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
//单图片上传 token:七牛上传token;types:上传文件前缀
function chatI(that, token, domain,types) {
  initQiniu(token, domain);
  // 微信 API 选文件
  wx.chooseImage({
    count: 1,
    success: function (res) {
      console.log(res)
      if (that.data.fileArr.length > 0){
        deleteFile(that.data.fileArr[0].file.key)
      }
      let filePath = res.tempFilePaths[0];
      let obj = {
        tempFilePaths: filePath
      }
      let arr = []
      arr.push(obj)
      that.setData({
        tempFilePaths: filePath,
        fileJudge:true,
        fileArr:arr
      })
    let houzhui = filePath.lastIndexOf(".")
    let sss = filePath.slice(houzhui)
    let keys = filePath.slice(houzhui - 5, houzhui)
    let timestamp = (new Date()).getTime();
    let fileName = types + timestamp + keys + sss
      
      // 交给七牛上传
      qiniuUploader.upload(filePath, fileName,(ser) => {
        console.log(ser)
        let fileArr = that.data.fileArr
        fileArr[0].file = ser
        that.setData({
          fileArr: fileArr
        })
        console.log(fileArr)

        // that.setData({
        //   'imageObject': ser
        // });
      }, (error) => {
        console.error('error: ' + JSON.stringify(error));
      },
        null,// 可以使用上述参数，或者使用 null 作为参数占位符
        (progress) => {
          that.setData({
            progressNum: progress.progress
          })
          // console.log('上传进度', progress.progress)
          // console.log('已经上传的数据长度', progress.totalBytesSent)
          // console.log('预期需要上传的数据总长度', progress.totalBytesExpectedToSend)
          if (progress.progress == 100){
            that.setData({
              fileJudge:false
            })
          }
        }, cancelTask => that.setData({ cancelTask })
      );
    }
  })
}
//删除七牛云图片
function deleteFile(fileKey){
  console.log(fileKey)
  let obj = {
    fileName: fileKey
  }
  connector.getFunc(app.conUser + connector.connector().fileDelete, obj, "post", app.tokens, function (res) {
    // console.log(res.data[0].upToken)
    console.log(res)

  }, function (res) {
    console.log(res)

  })
}
//多图片上传 token:七牛上传token;types:上传文件前缀
function chatIs(that, token, domain,types) {
  initQiniu(token, domain);
  // 微信 API 选文件
  wx.chooseImage({
    count: 1,
    success: function (res) {
      console.log(res)
      let filePath = res.tempFilePaths[0];
      let houzhui = filePath.lastIndexOf(".")
      let sss = filePath.slice(houzhui)
      let keys = filePath.slice(houzhui - 5, houzhui)
      let timestamp = (new Date()).getTime();
      let fileName = types + timestamp + keys + sss
      let obj = {
        tempFilePaths: filePath,
        key: fileName,
        fileJudge: true
      }
      let arr = that.data.fileArr
      arr.push(obj)
      that.setData({
        fileJudge:true,
        fileArr:arr
      })
      // 交给七牛上传
      qiniuUploader.upload(filePath, fileName,(ser) => {
        console.log(ser)
        let fileArrNew = that.data.fileArr
        for (let i = 0; i < fileArrNew.length; i++){
          if (fileArrNew[i].key == ser.key){
            fileArrNew[i].file = ser
            fileArrNew[i].fileJudge = false
          }
        }
        that.setData({
          fileArr: fileArrNew
        })
        console.log(fileArrNew)
      }, (error) => {
        console.error('error: ' + JSON.stringify(error));
      },
        null,// 可以使用上述参数，或者使用 null 作为参数占位符
        (progress) => {
          that.setData({
            progressNum: progress.progress
          })
          // console.log('上传进度', progress.progress)
          // console.log('已经上传的数据长度', progress.totalBytesSent)
          // console.log('预期需要上传的数据总长度', progress.totalBytesExpectedToSend)
          if (progress.progress == 100){
            that.setData({
              fileJudge:false
            })
          }
        }, cancelTask => that.setData({ cancelTask })
      );
    }
  })
}
